Spring Framework:4.3.14.RELEASE
在了解了依赖注入后接着来详细演示不同情景的依赖注入。
属性值直接注入
原始类型,字符串等可以直接属性值注入
1 | <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> |
Spring Framework 可以自动将字符串的属性值按最佳的匹配方式为对应的属性进行转换
为了简化配置,Spring Framework 提供了 P 属性命名空间:
1 | <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> |
Spring Framework 还支持 Properties 属性方式注入:
1 | <bean id="mappings" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> |
引用属性注入
使用 ref 属性:
1 | <bean id="user" class="com.example.spring.User"> |
使用 ref 子标签:
1 | <bean id="theTargetBean" class="..."/> |
使用 idref 子标签:
1 | <bean id="theTargetBean" class="..."/> |
直接使用 value 属性:
1 | <bean id="theTargetBean" class="..." /> |
内部类
1 | <bean id="outer" class="..."> |
内部类 Bean 没有 id 属性,不可以被其他 Bean 引用
集合注入
集合注入支持 list、 set、 map、 properteis
集合元素可以是原始类型和引用类型
1 | <bean id="moreComplexObject" class="example.ComplexObject"> |
支持集合合并:
1 | <beans> |
同理 list map set 均可以支持集合合并,且子集会继承并覆盖父集的值
必须在子集上指定 merge 属性值为 true
null 和 空字符串注入
1 | <bean class="ExampleBean"> |
1 | <bean class="ExampleBean"> |